package MultiThread.q1116;

import java.util.function.IntConsumer;

public class ZeroEvenOdd_1 {
    private int n;
    private volatile int flag = 1;

    public ZeroEvenOdd_1(int n) {
        this.n = n;
    }
    /*
    交替的打印 但是需要为01020304的形式
     */
    // printNumber.accept(x) outputs "x", where x is an integer.

    // IntConsumer printNumber
    public void zero() throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            synchronized (this) {
                while (flag % 2 == 0) wait();
                // printNumber.accept(0);
                System.out.print(0);
                flag++;
                notifyAll();
            }
        }
    }

    public void even() throws InterruptedException {
        for (int i = 2; i <= n; i += 2) {
            synchronized (this) {
                while (flag % 4 != 0) wait();
                // printNumber.accept(i);
                System.out.print(i);
                flag++;
                notifyAll();
            }
        }
    }

    public void odd() throws InterruptedException {
        for (int i = 1; i <= n; i += 2) {
            synchronized (this) {
                while (flag % 4 != 2) wait();
                // printNumber.accept(i);
                System.out.print(i);
                flag++;
                notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        ZeroEvenOdd_1 z = new ZeroEvenOdd_1(5);
        printT p1 = new printT(z, 1);
        printT p2 = new printT(z, 2);
        printT p3 = new printT(z, 3);
        new Thread(p1).start();
        new Thread(p2).start();
        new Thread(p3).start();
    }
}
class printT implements Runnable {
    private ZeroEvenOdd_1 z;
    private int mode;
    private printT() {

    }
    public printT(ZeroEvenOdd_1 z, int mode) {
        this.z = z;
        this.mode = mode;
    }
    @Override
    public void run() {
        try {
            if (mode == 1) {
                z.zero();
            } else if (mode == 2) {
                z.odd();
            } else {
                z.even();
            }
        } catch (Exception e) {

        }
    }
}